package spotGUI.floatingChatGUI;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.net.URL;
import java.util.Collections;
import java.util.LinkedList;
import java.util.Properties;

import javax.swing.ImageIcon;
import javax.swing.JTextPane;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;

import utils.StackTracePrinter;

public class ShortcutsParser {

	public static final String FILE_PATH = "options/emoticonShortcuts.properties";
	private Properties shortcuts = new Properties();
	
	private LinkedList<String> shortcutsList;
	private BufferedReader reader;
	private int i = 0;
	
	public ShortcutsParser () {

		try {
			shortcuts.load(new FileReader(FILE_PATH));
		} catch (Exception e) {
			StackTracePrinter.print(e);
		}
		
		
		shortcutsList = new LinkedList<String>();
		try {
			reader = new BufferedReader(new FileReader(FILE_PATH));
		} catch (FileNotFoundException e) {
			StackTracePrinter.print(e);
		}
		try {
			String line;
			while ((line = reader.readLine()) != null) {
				line = removeChar(line, '\\');
				shortcutsList.add(line.substring(0, line.indexOf('=')));
			}
		} catch (IOException e) {
			StackTracePrinter.print(e);
		}
	}

	public void parse (JTextPane source) throws BadLocationException {

		int count = 0;
		LinkedList<String> temp = null;
		Document doc = source.getDocument();

		for (; i < doc.getLength(); i++) {

			if (count==0) {
				temp = (LinkedList<String>) shortcutsList.clone();
				Collections.copy(shortcutsList, temp);
			}

			for (int j = 0; j < temp.size(); j++) {
				if (temp.get(j).charAt(count) != doc.getText(i, 1).charAt(0)) {
					temp.remove(j);
					j--;
				}
			}
			if (temp.size() == 0) {
				count = 0;
			} else if (temp.size() == 1 && count==temp.get(0).length()-1) {
				swapShortcutWithImage(temp.get(0), source, i, count);
				i = i-count;
				count=0;
			} else {
				count++;
			}
		}

	}

	private void swapShortcutWithImage (String shortcut, JTextPane source, int position, int count) {
		URL path = ShortcutsParser.class.getResource("/images/Emoticons/"+shortcuts.getProperty(shortcut));
		try {
			source.select(position-count, position+1);
			source.insertIcon(new ImageIcon(path));
		} catch (Exception e) {
			StackTracePrinter.print(e);
		}

	}

	private String removeChar(String s, char c) {
		StringBuffer r = new StringBuffer( s.length() );
		r.setLength( s.length() );
		int current = 0;
		for (int i = 0; i < s.length(); i ++) {
			char cur = s.charAt(i);
			if (cur != c) r.setCharAt( current++, cur );
		}
		return r.toString();
	}

	
	public LinkedList<String> getShortcuts() {
		return shortcutsList;
	}
	
	

}
